#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 11-Nov-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.ComponentModel;

using Thn;
using System.Windows.Forms;
#endregion

namespace Thn.Interface.Vcl
{
    /// <summary>
    /// Base class for editboxes that support a popup form.
    /// </summary>
    [ToolboxItem(false)]
#if DEBUG
    public
#else
    public
#endif
 abstract class OldPopupBoxBase : EditBox
    {
        #region Fields
        /// <summary>
        /// This will be used when PopupWidth is not specified.
        /// </summary>
        protected int mDefaultPopupWidth = 0;
        /// <summary>
        /// This will be used when PopupHeight is not specified.
        /// </summary>
        protected int mDefaultPopupHeight = 0;
        /// <summary>
        /// Whether property PopupWidth has been set.
        /// </summary>
        protected bool PopupWidthAssigned = false;
        /// <summary>
        /// Determine whether the popup edit will be showed or not when user press Enter key.
        /// </summary>
        protected bool mIsShowPopupOnKeyPress = true;

        /// <summary>
        /// Type of triggering popup behavior.
        /// </summary>
        protected PopupTrigger mPopupTrigger = PopupTrigger.KeyPress | PopupTrigger.MouseClicked;
        #endregion

        #region Properties

        #region Controller
        PopupController mController = null;
        /// <summary>
        /// Gets the popup controller.
        /// </summary>
        [Browsable(false), DefaultValue(null)]
        protected PopupController Controller
        {
            get { return mController; }
        }
        #endregion

        #region Editor
        /// <summary>
        /// Gets the popup editor. If assigned, this editor is reused eachtime a popup is shown.
        /// </summary>
        protected IPopupEditor mEditor = null;
        /// <summary>
        /// Gets the popup editor. If assigned, this editor is reused eachtime a popup is shown.
        /// </summary>
        [Browsable(false), DefaultValue(null)]
        protected IPopupEditor Editor
        {
            get { return mEditor; }
        }
        #endregion

        #region Editor Type
        /// <summary>
        /// Gets/Sets type of editor. If Editor is not assigned, this type is used to create a new editor instance each time a popup is shown.
        /// </summary>
        protected Type mEditorType = null;
        /// <summary>
        /// Gets/Sets type of editor. If Editor is not assigned, this type is used to create a new editor instance each time a popup is shown.
        /// </summary>
        [Browsable(false), DefaultValue(null)]
        protected Type EditorType
        {
            get { return mEditorType; }
            set { mEditorType = value; }
        }
        #endregion

        #region Is Popping
        /// <summary>
        /// Checks whether popup is showing.
        /// </summary>
        public bool IsPopping
        {
            get
            {
                bool result = false;
                if (mController != null) result = mController.IsPopping;
                return result;
            }
        }
        #endregion

        #region Popup Width
        /// <summary>
        /// Gets or Sets the width of popupform.
        /// Set to zero to use default width.
        /// </summary>
        protected int mPopupWidth = 0;
        /// <summary>
        /// Gets or Sets the width of popupform.
        /// Set to zero to use default width
        /// </summary>
        [Browsable(true), DefaultValue(0), Category("Appearance"), Description("Set to zero to use default value")]
        public int PopupWidth
        {
            get { return mPopupWidth; }
            set
            {
                mPopupWidth = value;
                PopupWidthAssigned = true;
            }
        }
        #endregion

        #region Popup Height
        /// <summary>
        /// Gets or Sets the Height of popupform.
        /// Set to zero to use default Height.
        /// </summary>
        protected int mPopupHeight;
        /// <summary>
        /// Gets or Sets the Height of popupform.
        /// Set to zero to use default Height
        /// </summary>
        [Browsable(true), DefaultValue(0), Category("Appearance"), Description("Set to zero to use default value")]
        public int PopupHeight
        {
            get { return mPopupHeight; }
            set
            {
                mPopupHeight = value;
            }
        }
        #endregion

        #region Render Context
        private PopupBoxBaseRenderContext mRenderContext;
        /// <summary>
        /// Gets reference to current renderation context.
        /// </summary>
        protected PopupBoxBaseRenderContext RenderContext
        {
            get { return mRenderContext; }
        }
        #endregion

        #endregion

        #region Events

        #region Popup Accepted
        /// <summary>
        /// This event is raised after popup is accepted.
        /// </summary>
        public event EventHandler PopupAccepted;

        /// <summary>
        /// Invoke event PopupAccepted.
        /// </summary>
        protected void RaisePopupAccepted(EventArgs args)
        {
            EventHandler handler = PopupAccepted;
            if (handler != null) handler(this, args);
        }
        #endregion

        #region Popup Canceled
        /// <summary>
        /// This event is raised after popup is canceled.
        /// </summary>
        public event EventHandler PopupCanceled;

        /// <summary>
        /// Invoke event PopupCanceled.
        /// </summary>
        protected void RaisePopupCanceled(EventArgs args)
        {
            EventHandler handler = PopupCanceled;
            if (handler != null) handler(this, args);
        }
        #endregion

        #endregion

        #region Base methods

        #region On Popup Accepted
        /// <summary>
        /// This method is raised after the user closed popup editor and wish to accept modifications on editor
        /// </summary>
        /// <param name="popup">The controller which manages the popup</param>
        protected virtual void OnPopupAccepted(PopupController popup)
        {

        }
        #endregion

        #region On Popup Canceled
        /// <summary>
        /// This method is raised after the user closed popup editor and wish to discard modifications on editor
        /// </summary>
        /// <param name="popup">The controller which manages the popup</param>
        protected virtual void OnPopupCanceled(PopupController popup)
        {

        }
        #endregion

        #region On Show Popup
        /// <summary>
        /// This method is raised before a popup is shown. Override this method to assign the data that is going to be used by popup editor
        /// </summary>
        /// <param name="popup">The controller which manages the popup</param>
        protected virtual void OnShowPopup(PopupController popup)
        {
            //set focus to txt
            if (!Inner.Focused) Inner.Focus();
        }
        #endregion

        #region On Get Popup Width
        /// <summary>
        /// Calculate the popup width
        /// </summary>
        protected virtual int OnGetPopupWidth()
        {
            int result = 0;

            if (mPopupWidth > 0) result = mPopupWidth;
            else if (mDefaultPopupWidth > 0) result = mDefaultPopupWidth;

            return result;
        }
        #endregion

        #region On Get Popup Height
        /// <summary>
        /// Calculate the popup height
        /// </summary>
        protected virtual int OnGetPopupHeight()
        {
            int result = 0;

            if (mPopupHeight > 0) result = mPopupHeight;
            else if (mDefaultPopupHeight > 0) result = mDefaultPopupHeight;

            return result;
        }
        #endregion

        #region On Drop Button Down
        /// <summary>
        /// Override this method for process show popup edit when user click on the drop button.
        /// </summary>
        protected override void OnDropButtonDown(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnDropButtonDown(e);

            if (IsPopping) CancelPopup();
            else ShowPopup();
        }
        #endregion

        #endregion

        #region Inner methods

        #region Prepare Popup
        /// <summary>
        /// Initialize popup editor.
        /// </summary>
        protected virtual void PreparePopup()
        {
            mController = new PopupController();
            mController.Host = this;
            if (mEditor != null) mController.Editor = mEditor;
            else if (mEditorType != null) mController.EditorType = mEditorType;
            else throw new Exception("Please assign value to either Editor or EditorType");
            mController.Width = OnGetPopupWidth();
            mController.Height = OnGetPopupHeight();

            //wire events
            mController.Accepted += new EventHandler(mController_Accepted);
            mController.Canceled += new EventHandler(mController_Canceled);
        }
        #endregion

        #region Clean Popup
        /// <summary>
        /// Unwire popup events and set controller to null
        /// </summary>
        void CleanPopup()
        {
            if (mController != null)
            {
                mController.Accepted -= new EventHandler(mController_Accepted);
                mController.Canceled -= new EventHandler(mController_Canceled);
                mController = null;
            }
        }
        #endregion

        #endregion

        #region Event processes
        void mController_Canceled(object sender, EventArgs e)
        {
            //delegate to descendant
            OnPopupCanceled(mController);

            //raise event
            RaisePopupCanceled(e);

            //clean up resources
            CleanPopup();
        }
        void mController_Accepted(object sender, EventArgs e)
        {
            //delegate to descendant
            OnPopupAccepted(mController);

            //raise event
            RaisePopupAccepted(e);

            //clean up resources
            CleanPopup();
        }

        #region Notify On Key Press
        /// <summary>
        /// Override this method for process the popup when user press some special key such as ESC or Enter.
        /// </summary>
        /// <param name="e"></param>
        internal override void NotifyInnerTextBoxOnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
        {
            base.NotifyInnerTextBoxOnKeyPress(e);

            if (e.KeyChar == (int)Keys.Escape)
            {
                if (IsPopping) CancelPopup();
                e.Handled = true;
            }
            else if (e.KeyChar == (int)Keys.Enter)
            {
                if (IsPopping) AcceptPopup();
                e.Handled = true;
            }
            else
            {
                //popup if not already so
                if ((!IsPopping) && (mIsShowPopupOnKeyPress)) ShowPopup();
                #region Defensive tracing
                else
                {
                    // the popup editor is not allow to show.
                }
                #endregion
            }
        }
        #endregion

        #region Notify Process Dialog Key
        /// <summary>
        /// Override this method for prevent process when user press dialog key.
        /// </summary>
        internal override bool NotifyInnerTextBoxProcessDialogKey(Keys keyData)
        {
            return false;
        }
        #endregion

        #region Notify Process Cmd Key
        /// <summary>
        /// Override this method for process the popup when user press Tab key.
        /// </summary>
        internal override bool NotifyProcessCmdKey(ref Message msg, Keys keyData)
        {
            bool handled = false;
            if (keyData == Keys.Tab)
            {
                if (IsPopping)
                {
                    CancelPopup();
                }
                #region Defensive tracing
                else
                {
                    // Popup is already canceled.
                }
                #endregion
            }
            else handled = base.NotifyProcessCmdKey(ref msg, keyData);

            return handled;
        }
        #endregion

        #endregion

        #region Public
        #region Accept Popup
        /// <summary>
        /// Close popup and accepts modifications made by popup editor
        /// </summary>
        public void AcceptPopup()
        {
            if (IsPopping) mController.Accept();
        }
        #endregion

        #region Cancel Popup
        /// <summary>
        /// Close popup and discard modifications made by popup editor
        /// </summary>
        public void CancelPopup()
        {
            if (IsPopping) mController.Accept();
        }
        #endregion

        #region Show Popup
        /// <summary>
        /// Show the popup editor
        /// </summary>
        public void ShowPopup()
        {
            if (!IsPopping)
            {
                //setup new controller
                PreparePopup();

                //delegate to descendant
                OnShowPopup(mController);

                //bring up popup
                mController.Show();

                // set editor
                mEditor = mController.Editor;
            }
        }
        #endregion
        #endregion

        #region On Create Render Context
        /// <summary>
        /// Create a new render context instance.
        /// </summary>
        protected override EditBoxRenderContext OnCreateRenderContext()
        {
            return mRenderContext;
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Create an empty instance. Must assign value for mEditor.
        /// </summary>
        protected OldPopupBoxBase() { }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public OldPopupBoxBase(Type editorType)
        {
            mRenderContext = new PopupBoxBaseRenderContext();
            mEditorType = editorType;
            mShowDropButton = true;

            if (!DesignMode)
            {
                InvalidateLayout();
            }
            #region Defensive tracing
            else
            {
                // just project in runtime mode only.
            }
            #endregion
        }
        #endregion
    }
}